<?php
/**
 *
 * @author     Daniel Botelho <botelho.daniel@gmail.com>
 */
class JSFunction
{
  private $name;
  private $args;
  private $content;
  private $variables;
  
  public static function addJSTags($content)
  {
  	return "<script type=\"text/javascript\">$content</script>";
  }
  
  public static function addJSOpenTag(JSFunction $function=null)
  {
  	$html = "<script type=\"text/javascript\">\n";
  	if($function)
  	  $html.= 'function '. $function->getName() .'('. $function->getArgs() .") {\n";
  	return $html;
  }
  
  public static function addJSCloseTag(JSFunction $function=null)
  {
  	$html = '';
  	if($function)
  	  $html.= "\n}\n";
  	$html.= "</script>\n";
  	return $html;
  }

  /**
   * @deprecated Usar antes o $func->__toString()
   */
  public static function renderFunction(JSFunction $func)
  {
    return "$func";
  }

  function __construct($name=null,$args=null,$content=null)
  {
    if($name) $this->setName($name);
    if($args) $this->setArgs($args);
    $this->variables = array();
    if($content) $this->setContent($content);
  }
  public function isClosure()
  {
    return ($this->getName())? false : true;
  }

  public function getName(){ return $this->name; }
  public function setName($name){ $this->name = $name; }

  public function getArgs(){ return $this->args; }
  public function setArgs($args){ $this->args = $args; }

  /**
   * @return string This Javascript Function content
   */
  public function getContent()
  {  
  	if($this->content || $this->variablesToString())
  	  return $this->variablesToString()."\n".$this->content; 
  }
  
  /**
   * Appends content to this javascript function
   *
   * @param string $content
   */
  public function addContent($content)
  {
    $this->content = ($this->content)? $this->content."\n".$content : $content;
  }
    
  public function setContent($content){ $this->content = $content; }
  
  public function addVariable(JSVariable $variable){ $this->variables[] = $variable; }
  
  public function getVariables(){ return $this->variables; }
  public function setVariables($variables){ $this->variables = variables; }
  
  private function variablesToString()
  {

  	$jscode = null;
  	foreach ($this->variables as $variable) {
  		$jscode.= "$variable";
  	}
  	
  	return $jscode; 
  }

  public function __toString()
  {
    return 'function '. $this->getName() .'('. $this->getArgs() .") {\n" .
      $this->getContent()."\n}\n";
  }

  
}
